package puj.promobil.prometer.fragmento;

import java.util.ArrayList;
import java.util.List;

import puj.promobil.prometer.ActivityDetalleProductoSingle;
import puj.promobil.prometer.ListenerFindProducto;
import puj.promobil.prometer.ListenerSelectEmpresa;
import puj.promobil.prometer.ProductosActivity;
import puj.promobil.prometer.R;
import puj.promobil.prometer.adapters.ItemProductoAdapter;
import puj.promobil.prometer.dto.Empresa;
import puj.promobil.prometer.dto.Producto;
import puj.promobil.prometer.persistence.DatabaseManager;
import android.app.Activity;
import android.app.Fragment;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Spinner;
import android.widget.Toast;

public class ProductoLista extends Fragment {

	protected ListView lista_productos = null;
	private SearchView tv1;
	private Button bot2;
	private Spinner empresas;

	private ProductosActivity actividad;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		DatabaseManager.init(actividad);
		
		View view = inflater
				.inflate(R.layout.lista_prodcutos, container, false);
		
		try {
			
			
			
			bot2 = (Button) view.findViewById(R.id.botoncito2);
			tv1 = (SearchView) view.findViewById(R.id.searchView1);
			empresas = (Spinner) view.findViewById(R.id.empresaspinner);
			

			bot2.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					Intent intent = new Intent(
							"com.google.zxing.client.android.SCAN");
					intent.putExtra("SCAN_MODE", "BARCODE_MODE");
					startActivityForResult(intent, 0);
				}
			});
			
			lista_productos = (ListView) view
					.findViewById(R.id.lista_productos);

			ItemProductoAdapter adapter = new ItemProductoAdapter(actividad,
					new ArrayList<Producto>());

			lista_productos.setAdapter(adapter);

			lista_productos.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> adapt, View view,
						int position, long id) {

					
					//TODO asda
					actividad.cargarDetalleProducto((int)id);

				}
			});

			SearchManager searchManager = (SearchManager) actividad
					.getSystemService(Context.SEARCH_SERVICE);
			tv1.setSearchableInfo(searchManager.getSearchableInfo(actividad
					.getComponentName()));
			tv1.setOnQueryTextListener(new ListenerFindProducto(actividad, lista_productos));
			
			addEmpresas();
		} catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(actividad.getBaseContext(), e.getMessage(),
					Toast.LENGTH_LONG).show();

		}
		empresas.requestFocus();
		getActivity().getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		return view;
	}

	// May also be triggered from the Activity
	public void updateDetail() {
		/*
		 * String newTime = String.valueOf(System.currentTimeMillis());
		 * ProdutoDetalle fragment = (ProdutoDetalle) getFragmentManager()
		 * .findFragmentById(R.id.detailFragment); if (fragment != null &&
		 * fragment.isInLayout()) { //fragment.setText(newTime); } else {
		 * 
		 * //falta clase Intent intent = new
		 * Intent(getActivity().getApplicationContext(),
		 * ActivityDetalleProductoSingle.class); intent.putExtra("value",
		 * newTime); startActivity(intent);
		 * 
		 * }
		 */
	}

	private void addEmpresas() throws Exception {

		List<Empresa> listaempresas = DatabaseManager.getInstance()
				.getAllEmpresa();
		List<String> razones = new ArrayList<String>();

		for (Empresa val1 : listaempresas) {
			razones.add(val1.getRazon());
		}

		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(actividad,
				android.R.layout.simple_spinner_item, razones);
		dataAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		empresas.setAdapter(dataAdapter);

		empresas.setOnItemSelectedListener(new ListenerSelectEmpresa(actividad));

	}

	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
		actividad = (ProductosActivity) activity;
	}
	
	
	public void setBarCode(String carcode){
		tv1.setQuery(carcode.subSequence(0, carcode.length()), true);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
			if (requestCode == 0) {
				if (resultCode == Activity.RESULT_OK) {
					String contents = intent.getStringExtra("SCAN_RESULT");
					
				    this.setBarCode(contents);
				      
				}
			}
			
	    }
}
